//
//  SMSCodeVC.m
//  SHShopping
//
//  Created by 坤鼎 on 2019/9/5.
//  Copyright © 2019 kunding. All rights reserved.
//

#import "SMSCodeVC.h"
#import "RegisterSetUserInfoVC.h"
#import "RefreshLineView.h"
#import "MainTabBarVC.h"

@interface SMSCodeVC () <UITextFieldDelegate>

@property (nonatomic, strong) UIButton *btnLogo;

@property (nonatomic, strong) UITextField *tf;

@property (nonatomic, strong) UIButton *btnOK;

@property (nonatomic, strong) UIButton *btnCode;
/**
 UITextField 字符最大长度
 */
@property (nonatomic, assign) NSInteger textlength;

@end

@implementation SMSCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textlength = 4;
    [self setNav];
    [self initView];
}

- (void)initView {
    
    CGFloat bage = ADAPT_W(31);
    
    self.btnLogo = [[UIButton alloc] initWithFrame:CGRectMake(bage, 53, 64, 64)];
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(12 + GetViewXW(self.btnLogo), 66, 200, 39)];
    
    UILabel *lbPhoneNum = [[UILabel alloc] initWithFrame:CGRectMake(bage, GetViewYH(self.btnLogo) + 10, SCREEN_WIDTH - bage - bage - 51, 20)];
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - bage - 47, GetViewYH(self.btnLogo), 47, 40)];

    self.tf = [[UITextField alloc] initWithFrame:CGRectMake(bage, GetViewYH(lbTitle) + 102, ADAPT_W(190), 44)];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(bage, GetViewYH(self.tf), GetViewWidth(self.tf), 0.5)];
    self.btnOK = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 77) / 2, GetViewYH(lineView) + 64, 77, 77)];
    UIButton *btnBottom = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 44 - 32 - kNavBarAndStatusBarHeight, SCREEN_WIDTH, 44)];
    _btnCode = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - bage - ADAPT_W(109), GetViewY(self.tf), ADAPT_W(109), 44)];
    
    [self.view addSubview:self.btnLogo];
    [self.view addSubview:lbTitle];
    [self.view addSubview:btnBack];
    [self.view addSubview:lbPhoneNum];
    [self.view addSubview:self.tf];
    [self.view addSubview:lineView];
    [self.view addSubview:self.btnOK];
    [self.view addSubview:btnBottom];
    [self.view addSubview:_btnCode];
    
    [self.btnLogo setImage:ImageNamed(@"启动页png") forState:UIControlStateNormal];
    
    lbTitle.text = @"输入验证码";
    lbTitle.font = FONT_BOLD(28);
    
    self.tf.placeholder = @"请输入验证码";
    self.tf.delegate = self;
    self.tf.font = FONT_BOLD(24);
    self.tf.keyboardType = UIKeyboardTypeNumberPad;
 
    lineView.backgroundColor = UIColorFromRGB(0xDDDDDD);
    
    [self.btnOK setImage:ImageNamed(@"login_Next_N") forState:UIControlStateNormal];
    self.btnOK.userInteractionEnabled = NO;
    [self.btnOK addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
 
    NSString *str = [NSString stringWithFormat:@"验证码已发送至 +86 %@", self.phoneNum];
    CGFloat width = [self getWidthWithStr:str];
    lbPhoneNum.text = str;
    lbPhoneNum.frame = CGRectMake(bage, GetViewYH(self.btnLogo) + 10, width, 20);
    lbPhoneNum.textColor = UIColorFromRGB(0x999999);
    lbPhoneNum.font = FONT(13);
    
    btnBack.frame = CGRectMake(GetViewXW(lbPhoneNum) + 15, GetViewYH(self.btnLogo), 70, 40);
    [btnBack setImage:[UIImage imageNamed:@"login返回"] forState:UIControlStateNormal];
    [btnBack setTitleColor:UIColorFromRGB(0x555555) forState:UIControlStateNormal];
    btnBack.titleLabel.font = FONT(13);
    [btnBack setTitle:@"  修改" forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    _btnCode.titleLabel.font = FONT(14);
    _btnCode.layer.cornerRadius = 22;
    _btnCode.layer.masksToBounds = YES;
    _btnCode.layer.borderWidth = 1;
    _btnCode.layer.borderColor = UIColorFromRGB(0x3170FF).CGColor;
    [_btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_btnCode setTitleColor:UIColorFromRGB(0x3170FF) forState:UIControlStateNormal];
    [_btnCode addTarget:self action:@selector(codeAction) forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:@"登录即代表阅读并同意服务协议"];
    [attriStr addAttribute:NSFontAttributeName value:FONT_BOLD(13) range:NSMakeRange(10, 4)];
    [btnBottom setAttributedTitle:attriStr forState:UIControlStateNormal];
    btnBottom.titleLabel.font = FONT(12);
    [btnBottom addTarget:self action:@selector(actionAgreement) forControlEvents:UIControlEventTouchUpInside];
    btnBottom.hidden = YES;
}

- (void)actionAgreement {
    WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:@"https://www.baidu.com/duty/"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 获取字符串长度
 
 @param text 字符串
 @return 字符串长度
 */
- (CGFloat)getWidthWithStr:(NSString *)text {
    CGFloat width = [text boundingRectWithSize:CGSizeMake(KScreenWidth, 20) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: FONT(13)} context:nil].size.width;
    return width;
}

#pragma mark - action 获取验证码
- (void)codeAction {
    NSDictionary *par = @{@"mobile":self.phoneNum};
    
    [SXLoadingView showProgressHUD:nil];
    [PPNetworkHelper POST:URL_smsSend parameters:par success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue] == YES) {
            [SXLoadingView hideProgressHUD];
            [self openCountdown];
        } else {
            [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingErrorTime];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingErrorTime];
    }];
}
// 开启倒计时效果
- (void)openCountdown {
    __block NSInteger time = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.btnCode setTitleColor:UIColorFromRGB(0x3170FF) forState:UIControlStateNormal];
                self.btnCode.layer.borderColor = UIColorFromRGB(0x3170FF).CGColor;
                self.btnCode.userInteractionEnabled = YES;
            });
        } else {
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.btnCode setTitle:[NSString stringWithFormat:@"重新获取(%.2ds)", seconds] forState:UIControlStateNormal];
                [self.btnCode setTitleColor:UIColorFromRGB(0x555555) forState:UIControlStateNormal];
                self.btnCode.layer.borderColor = UIColorFromRGB(0xDDDDDD).CGColor;
                self.btnCode.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
#pragma mark - 登录
- (void)loginAction {
    [self.tf resignFirstResponder];
    
    NSString *phoneNum = [self.phoneNum stringByReplacingOccurrencesOfString:@" "withString:@""];
    NSString *code = [self.tf.text stringByReplacingOccurrencesOfString:@" "withString:@""];
    NSDictionary *par = @{@"mobile":phoneNum,
                          @"code":code
                          };
    [SXLoadingView showProgressHUD:@""];
    [PPNetworkHelper POST:URL_appLogin parameters:par success:^(id responseObject) {
        
        if ([responseObject[@"success"] integerValue] == 1) {
            [SXLoadingView hideProgressHUD];
            
            NSString *uid = DSStringValue(responseObject[@"retBody"][@"userId"]);
            NSString *nickName = DSStringValue(responseObject[@"retBody"][@"nickName"]);
            NSString *usermobil = DSStringValue(responseObject[@"retBody"][@"mobile"]);
            NSString *userimage = DSStringValue(responseObject[@"retBody"][@"avatarUrl"]);
            
            if (IsNilString(nickName)) {
                nickName = @"早安上海";
                RegisterSetUserInfoVC *vc = [[RegisterSetUserInfoVC alloc] init];
                vc.uid = uid;
                vc.nickName = nickName;
                vc.usermobil = usermobil;
                vc.userimage = userimage;
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                NSDictionary *dicData = @{@"uid":uid,
                                          @"mobile":usermobil,
                                          @"nickName":nickName,
                                          @"avatarUrl":userimage};
                [[UserManager sharedUserManager] updateUserInfo:dicData];
                [SXLoadingView showAlertHUD:@"登录成功" duration:1];
                
                MainTabBarVC *vc = [[MainTabBarVC alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = vc;
            }
        } else {
            [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingTime];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}





#pragma mark - textField代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = textField.text;
    NSDictionary *attrsDictionary =@{
                                     NSFontAttributeName:self.tf.font,
                                     NSKernAttributeName:[NSNumber numberWithFloat:25.0f]//这里修改字符间距
                                     };
    self.tf.attributedText = [[NSAttributedString alloc] initWithString:text attributes:attrsDictionary];
    
    
    
    
    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
    if (proposedNewLength >= self.textlength) {
        [self.btnOK setImage:ImageNamed(@"login_Next_Y") forState:UIControlStateNormal];
        self.btnOK.userInteractionEnabled = YES;
    } else {
        [self.btnOK setImage:ImageNamed(@"login_Next_N") forState:UIControlStateNormal];
        self.btnOK.userInteractionEnabled = NO;
    }
    
    if (proposedNewLength > self.textlength) {
        return NO;//限制长度
    } else {
        return YES;
    }
}

@end
